var System_Admin_Permission = function(options){

    this.module = options.module;
    this.controller = options.controller;
    this.urlPath = baseUrl + '/' + this.module + '/' + this.controller;
    this.initialize();
    this.sendding = false;
    this.obGridView = $("#jqxgrid");
}

System_Admin_Permission.prototype.initialize = function(){
    var self = this;
    this.loadTree();
    $('#UnitID').change(function(){
        self.rebuiltStaff($(this).val());
    })
    $('#viewpermission').click(function(){self.LoadRoles();})
    $('#setpermission').click(function(){self.SetRoles();})
    $('#removepermission').click(function(){self.removeRoles();})
    $('#refreshTree').click(function(){self.refresh();})
    
    $('#Save').click(function(){
        self.SaveRoles();
    })
}
System_Admin_Permission.prototype.initializeJqxGrid = function(){
    

}

$.extend(System_Admin_Permission.prototype, {
    _eSave: function(){
        var self = this;
        $("#btnsave").unbind('click').click(function(){
            if($('#frmUpdate')[0].checkValidity()){
                self.save();
                return false;
            }
        });
    },
    rebuiltStaff: function(UnitID){
        var self = this
            ,options = '';
        options = '<option value="">--- Chọn cán bộ ---</option>';
        for (var i = 0; i < arrStaff.length; i++) {
            if (arrStaff[i]['UnitID'] == UnitID)
                options += '<option value="'+arrStaff[i]['StaffID']+'">'+arrStaff[i]['Name']+'</option>';
        };
        $('#StaffID').html(options).refresh();

    },
} );
/*
 * Them moi
 * Creater : Truongdv
 */
System_Admin_Permission.prototype.loadTree=function (){
    var self = this
        ,url = this.urlPath + '/loadtree';
    var obj = $("#jsTree");
            obj.jstree({
            "plugins" : [ "themes","json_data", "ui","contextmenu","hotkeys","search","types","checkbox" ],
            "json_data" : { 
                "ajax" : {
                    "url" : url,
                    "data" : function (n) { 
                        return { 
                            "operation" : "get_children", 
                            "id" : n.attr ? n.attr("id").replace("node_","") : '',
                        }; 
                    }
                }
            }
            
            ,"types" : {
                "max_depth" : -2,
                "max_children" : -2,
                "valid_children" : [ "drive" ],
                "types" : {
                    "user" : {
                        "icon" : {
                            "image" : "../../../public/images/Users.png"
                        }
                    },
                    "group" : {
                        "icon" : {
                            "image" : "../../../public/images/user_group.png",
                            "check_node" : false,
                            "uncheck_node" : false
                        }
                    },
                    "home" : {
                               "icon" : {
                                   "image" : "../../../public/images/home.png",
                                   "check_node" : false,
                                   "uncheck_node" : false
                               }
                           } ,
                },
                "default" : {
                    "valid_children" : [ "default" ]
                }
            }
             ,"search" : {
                "ajax" : {
                    "url" : url,
                    "data" : function (str) {
                        return {
                            "operation" : "search",
                            "search_str" : str
                        };
                    }
                }
            }
            ,"themes" : {
                "theme" : "default",
                "dots" : true,
                "icons" : true,
                "url": baseUrl + '/public/lib-js/system/jsTree/themes/default/style.css'
                }
            ,contextmenu: {items: self.customersMenu}
            ,callback : {
                onrgtclk    : function() { jAlert(12); },
              }
        })
        .bind("select_node.jstree", function (event, data) {
                obj.jstree("toggle_node", data.rslt.obj);
                $('#idNode').val(data.rslt.obj.attr("id"));
                $('#nameNode').val(data.inst.get_text(data.rslt.obj));
            })
        .delegate("a.jstree-clicked", "click", function (event, data) {
                event.preventDefault();
            })
        .delegate("a","dblclick", function(e) {
            // jAlert(data.rslt.obj.parent().atrr('rel'))
        });

        var to = false;
        $('#searchNodes').keyup(function () {
        if(to) { clearTimeout(to); }
            to = setTimeout(function () {
                var v = $('#searchNodes').val();
            }, 250);
        });

}

System_Admin_Permission.prototype.genTable = function (data){
    var htmls =''
        ,iTotal = data.length
        ,StaffDefault =''
        ,index = 0
        ,checked = '';
    
    for (var i = 0; i < iTotal; i++) {
        if(StaffDefault != data[i]['StaffID']){
            StaffDefault = data[i]['StaffID'];
            htmls +='<tr><td colspan="3"><label st="'+StaffDefault+'" class="igroup iopen" onclick="group(this)" >'+data[i]['StaffName']+'</label></td></tr>';
            index = 0;
        }
        index ++;
        htmls +='<tr st="'+StaffDefault+'">';
        htmls +='<td align="center">'+index+'</td>';
        htmls +='<td>'+dLayout.getNameByCode(arrPerType,data[i]['Roles'])+'</td>';
        if (data[i]['DefaultSet'] == '1') {
            checked ="checked";
        }else{
            checked = '';
        }
        htmls +='<td align="center"><input type="checkbox" '+checked+' name="check_default" /></td>';
        htmls +='</tr>';
    };
    return htmls;
}
function group(obj){
    if($(obj).hasClass('iopen')){
        $(obj).removeClass('iopen').addClass('iclose');
        $('#table-data tr[st="'+$(obj).attr('st')+'"]').hide();
    }else{
        $(obj).removeClass('iclose').addClass('iopen');
        $('#table-data tr[st="'+$(obj).attr('st')+'"]').show();
    }
}
System_Admin_Permission.prototype.LoadRoles = function (){
    var self = this
        ,url = this.urlPath + '/roles'
        ,StaffIDList='';
    $("#jsTree").jstree("get_checked",null,true).each 
          (function () { 
            if($(this).attr('rel') == 'user')
                StaffIDList += this.id + ',';

     }); 
    StaffIDList = StaffIDList.substring(0,StaffIDList.length -1); 

    $.ajax({
        url: url,
        type: "POST",
        data: {StaffIDList:StaffIDList},
        dataType: 'json',
        success: function(data){
            $('table#table-data tr').not(':eq(0)').remove();
            $('table#table-data tr:eq(0)').after(self.genTable(data));
            $('#Tab01').trigger('click');
            dLayout.hideLoadPage();
        },
        beforeSend: function(xhr) {
            dLayout.showLoadPage();
        },
        errors: function(){
            dLayout.hideLoadPage();
        }
    }); 

}
System_Admin_Permission.prototype.removeRoles = function (){

}


System_Admin_Permission.prototype.customersMenu = function (node){
    var self = this;
    var nodeid = $(node).attr('id')
        ,nodeName = $(node).children('a:first').text()
        ,parentID = $(node).parent().parent().attr('id');
    var items = {};
    if ($(node).hasClass("staff")){
        items = {
            "ViewRoles" : {
                    "separator_before"  : true,
                    "separator_after"   : true,
                    "label"             : "<i></i><span class='vakata-contextmenu-sep'>&nbsp;</span>Xem quyền",
                    "action"            : function (obj) { $('#viewpermission').trigger('click'); }
                },
            "SetRoles" : {
                    "separator_before"  : true,
                    "separator_after"   : true,
                    "label"             : "<i></i><span class='vakata-contextmenu-sep'>&nbsp;</span>Phân quyền",
                    "action"            : function (obj) { $('#setpermission').trigger('click'); }
                },
            "DeleteRoles" : {
                    "separator_before"  : true,
                    "separator_after"   : true,
                    "label"             : "<i></i><span class='vakata-contextmenu-sep'>&nbsp;</span>Xóa quyền",
                    "action"            : function (obj) { $('#removepermission').trigger('click');  }
                },
        };
        
    }
        items.Refresh = {
                    "separator_before"  : true,
                    "separator_after"   : true,
                    "label"             : "<i></i><span class='vakata-contextmenu-sep'>&nbsp;</span>Refresh",
                    "action"            : function (obj) { 
                        $('#refreshTree').trigger('click');  
                        // self.refresh();
                    }
                }
    return items;
}
System_Admin_Permission.prototype.refresh = function (){
    var self = this
        ,url = this.urlPath + '/refresh';
    $.ajax({
        url: url,
        type: "POST",
        success: function(data){
            $("#jsTree").jstree("refresh");
            dLayout.hideLoadPage();
        },
        beforeSend: function(xhr) {
            dLayout.showLoadPage();
        },
        errors: function(){
            dLayout.hideLoadPage();
        }
    }); 
}

System_Admin_Permission.prototype.SetRoles = function (){
    var self = this
        ,url = this.urlPath + '/getpermision'
        ,StaffIDList=''
        ,iCount = 0
        ,oItem;
    $("#jsTree").jstree("get_checked",null,true).each 
          (function () { 
            if($(this).attr('rel') == 'user'){
                iCount ++;
                StaffIDList += this.id + ',';
            }

     });
    StaffIDList = StaffIDList.substring(0,StaffIDList.length -1); 
    if (StaffIDList =='') {
        jAlert('Bạn chưa chọn cán bộ nào để phân quyền', 'Thông báo');
        return false;
    };
    $('#hdn_staffid').val(StaffIDList);
    // permision_detail
    $('#permision_detail').find('input[type="checkbox"]').attr('checked',false);
    if (iCount > 1) {
        $('#Tab02').trigger('click');
        return false;
    };
    $.ajax({
        url: url,
        type: "POST",
        data: {StaffIDList:StaffIDList},
        dataType:'json',
        success: function(data){
            $('#Tab02').trigger('click');
            for (var i = 0; i < data.length; i++) {
                oItem = $('input#check-item[value="'+data[i]['Roles']+'"]');
                oItem.trigger('click');
                if (data[i]['DefaultSet'] == 1) {
                    oItem.parent().parent().find('#item-default').trigger('click');
                }
            };
            dLayout.hideLoadPage();
        },
        beforeSend: function(xhr) {
            dLayout.showLoadPage();
        },
        errors: function(){
            dLayout.hideLoadPage();
        }
    }); 
}

System_Admin_Permission.prototype.SaveRoles = function (){
    var self = this
        ,url = this.urlPath + '/saveroles'
        ,permission =[]
        ,pdefault =[];
    $('#permision_detail input#check-item:checked').each(function(){
        permission.push($(this).val());
        if($(this).parent().parent().find('#item-default').is(':checked')){
            pdefault.push('1');
        }else{
            pdefault.push('0');
        }
    })
    var data={StaffIDList: $('#hdn_staffid').val()
                ,permission:permission
                ,pdefault:pdefault
            }
    $.ajax({
        url: url,
        type: "POST",
        data: data,
        success: function(data){
            $('#Tab01').trigger('click');
            self.LoadRoles();
            $('#Tab-02').html('');
            dLayout.hideLoadPage();
        },
        beforeSend: function(xhr) {
            dLayout.showLoadPage();
        },
        errors: function(){
            dLayout.hideLoadPage();
        }
    });
}